<script setup lang="ts">
import Header from '@/components/Header.vue'
import Menu from '@/components/Menu.vue'
import MyBox from '@/components/MyBox.vue'
import SeamlessList from './components/SeamlessList.vue'
import UPHChart from './components/UPHChart.vue'
import ThrowsChart from './components/ThrowsChart.vue'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { useMessage } from '@/hooks/useMessage'
import { Query } from '@/api'
import Top3Chart from './components/Top3Chart.vue'

const { query } = useRoute()
//看板标题
const title = computed(() => {
  return query.label || ''
})

//工单信息
const data = ref<any[]>([])
const cols = ref<any[]>([])

//NPM信息
const getImageUrl = (name: string): string => {
  return new URL(`/src/assets/${name}.png`, import.meta.url).href
}

const imageCols = ref<any[]>([])
const imageList = ref<any[]>([])

const currentIndex = ref(-1)
const maxZIndex = ref(1)
const showCard = (index: number) => {
  maxZIndex.value += 1
  currentIndex.value = index
}

const closeCard = () => {
  currentIndex.value = -1
}

//刷新周期
const flushTimer = ref()
//底部责任人
const otherInfo = ref({
  PD: '',
  QA: '',
  PE: ''
})

//UPH图信息
const uphChartInfo = ref({
  xList: [],
  yList: []
})
//抛科数量
const throwsChartInfo = ref({
  xList: [],
  yList: []
})
//Top3
const top3ChartInfo = ref({
  xList: [],
  yList: [],
  rationList: []
})

//线别
const line = ref('')
const lineList = ref()
//切换线别
const changeLine = async () => {
  //获取责任人信息
  const match =
    lineList.value.length && lineList.value.filter((item: any) => item.Value == line.value)
  otherInfo.value = match.length && match[0]
  // 先关闭定时器再重新启动刷新周期
  stopTimer()
  //开始循环获取数据GetKBInfo
  startTimer()
}

//获取数据
const getKBInfo = async () => {
  const res = (await Query({
    inputStr: `GroupName=${query.groupName};$;JobType=${query.jobType};$;OperType=GetKBInfo;$;Key=Line;$;Line=${line.value}`
  })) as any
  if (res.code !== 200) {
    message.error(res.msg)
    return
  }
  const { woInfo, npmInfo, uphInfo, rejTOPInfo } = res.data
  imageList.value = npmInfo || []
  data.value = woInfo || []
  // 格式化图表信息
  uphChartInfo.value.xList = uphInfo.map((item: any) => item.TimeNode)
  uphChartInfo.value.yList = uphInfo.map((item: any) => item.Qty)

  throwsChartInfo.value.xList = npmInfo.map((item: any) => item.LocID)
  throwsChartInfo.value.yList = npmInfo.map((item: any) => item.RejQty)

  top3ChartInfo.value.xList = rejTOPInfo.map((item: any) => item.LocID).reverse()
  top3ChartInfo.value.yList = rejTOPInfo.map((item: any) => item.Qty).reverse()
  top3ChartInfo.value.rationList = rejTOPInfo.map((item: any) => item.Proportion).reverse()
}

const message = useMessage()
//获取页面信息
const getPageInfo = async () => {
  const res = (await Query({
    inputStr: `GroupName=${query.groupName};$;JobType=${query.jobType};$;OperType=Getpage`
  })) as any
  if (res.code !== 200) {
    message.error(res.msg)
    return
  }
  const { npmFieldInfo, ctInfo, woFieldInfo, lineInfo } = res.data
  lineList.value = lineInfo || []
  cols.value = woFieldInfo
  imageCols.value = npmFieldInfo
  //刷新时间
  flushTimer.value = ctInfo.length && ctInfo[0].CT
}

// 1.循环过程中，重新选择【线别】，关闭循环，选定【产品编号】后重新开始
// 2.循环过程中，重新选择【产品编号】，关闭循环并开始新循环

// 定义状态
const isRunning = ref(false)
const timerId = ref<number | null>(null)

// 开始定时器
const startTimer = async () => {
  if (isRunning.value) return // 防止重复启动

  isRunning.value = true
  console.log('定时器启动')

  // 立即执行一次
  await getKBInfo()

  // 设置定时器，每3分钟执行一次 (3分钟 = 3*60*1000 = 180000毫秒)
  const timer = flushTimer.value * 60 * 1000
  timerId.value = window.setInterval(getKBInfo, timer)
}

// 停止定时器
const stopTimer = () => {
  if (timerId.value) {
    window.clearInterval(timerId.value)
    timerId.value = null
    isRunning.value = false
    console.log('定时器已停止')
  }
}

// 组件卸载前清理定时器
onBeforeUnmount(() => {
  stopTimer()
})

onMounted(() => getPageInfo())
</script>
<template>
  <div class="w-full overflow-hidden my-page">
    <Header :title="`${title}` + '看板'" />
    <section class="board-content">
      <div class="flex justify-between row">
        <MyBox title="" style="width: 100%">
          <template v-slot:main>
            <SeamlessList :data="data" :cols="cols" />
          </template>
        </MyBox>
      </div>
      <div class="flex justify-between row">
        <MyBox title="贴片机状态" style="width: 100%">
          <template v-slot:main>
            <div class="flex flex-wrap items-center npm-info">
              <div
                v-for="(i, index) in imageList"
                :key="index"
                class="flex items-center image-card"
                @click="showCard(index)"
              >
                <img class="icon" :src="getImageUrl(i.Status)" />
                <div v-show="currentIndex === index" class="overlay" :style="{ zIndex: maxZIndex }">
                  <!-- <h3>
                    工作状态：<span>{{ i.title }}</span>
                  </h3> -->
                  <p v-for="(item, index) in imageCols" :key="index">
                    {{ item.label }}：<span>{{ i[item.value] || '' }}</span>
                  </p>
                  <p><span class="close-btn" @click.stop="closeCard">关闭</span></p>
                  <div class="arrow arrow-left arrow-delay"></div>
                </div>
              </div>
            </div>
          </template>
        </MyBox>
      </div>
      <div class="flex justify-between row">
        <MyBox title="UPH图信息" style="width: 40%">
          <template v-slot:main>
            <UPHChart :data="uphChartInfo" />
          </template>
        </MyBox>
        <MyBox title="抛科数量" style="width: calc(60% - 30px)">
          <template v-slot:extra>
            <p class="throws-top3-title" v-if="top3ChartInfo.xList.length">抛料TOP前3</p>
            <div class="throws-top3-chart">
              <Top3Chart :data="top3ChartInfo" />
            </div>
          </template>
          <template v-slot:main>
            <div class="throws">
              <ThrowsChart :data="throwsChartInfo" />
            </div>
          </template>
        </MyBox>
      </div>
      <div class="flex justify-between other-info">
        <MyBox title="" style="width: 100%">
          <template v-slot:main>
            <div class="flex items-center justify-between">
              <p>
                <el-select
                  v-model="line"
                  style="width: 170px"
                  placeholder="请选择线别"
                  @change="changeLine"
                >
                  <el-option
                    v-for="(item, index) in lineList"
                    :key="index"
                    :label="item.Label"
                    :value="item.Value"
                  />
                </el-select>
              </p>
              <p>生产责任人：{{ otherInfo.PD ?? '' }}</p>
              <p>质量责任人：{{ otherInfo.QA ?? '' }}</p>
              <p>工程责任人：{{ otherInfo.PE ?? '' }}</p>
            </div>
          </template>
        </MyBox>
      </div>
    </section>
    <Menu />
  </div>
</template>
<style lang="less" scoped>
.npm-info {
  margin-top: 10px;
  height: 200px;
  overflow-y: visible;
}
.throws {
  margin-top: 80px;
}
.throws-top3-title {
  position: absolute;
  top: 20px;
  right: 130px;
  font-size: 18px;
}
.throws-top3-chart {
  position: absolute;
  width: 300px;
  right: 10px;
  top: 10px;
}

.row-box-wrapper {
  overflow: visible;
}

.image-card {
  position: relative;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
  cursor: pointer;
  margin: 0 5px;
  width: calc((100% - 250px) / 25);
  .overlay {
    position: absolute;
    top: -200%;
    left: 50px;
    width: 300px;
    padding: 15px;
    transition: opacity 0.4s ease;
    border: 2px solid #00aeff;
    background: #040d4c;
    /* 左侧箭头 */
    .arrow {
      position: absolute;
      width: 0;
      height: 0;
      border-style: solid;
      transition: all 0.4s ease;
      // opacity: 0;
    }
    .arrow-left {
      top: 50%;
      left: -15px;
      transform: translateY(-50%);
      border-width: 15px 15px 15px 0;
      border-color: transparent rgba(46, 152, 201, 1) transparent transparent;
    }
    h3 {
      color: white;
      border: 2px solid #00aeff;
      span {
        display: inline-block;
        // float: right;
      }
      margin-bottom: 10px;
    }
    p {
      color: white;
      span {
        float: right;
        display: block;
      }
      margin-bottom: 10px;
    }
    .close-btn {
      color: #8fe1ff;
      border-radius: 2px;
      border: 1px solid #8fe1ff;
      padding: 2px 10px;
    }
  }
}

.row {
  margin: 15px auto 20px;
}
.icon {
  width: 100%;
}

.other-info {
  color: #8fe1ff;
  font-size: 24px;
  .flex {
    width: 99%;
    margin: 0 auto;
  }
}

.el-select-dropdown__item {
  font-size: 18px;
}
</style>
